﻿/*
 * 由SharpDevelop创建。
 * 用户： Administrator
 * 日期: 2017/2/4
 * 时间: 20:23
 * 
 * 要改变这种模板请点击 工具|选项|代码编写|编辑标准头文件
 */
using System;
using System.Net;

namespace MiniHttpServer
{
	/// <summary>
	/// Description of Server.
	/// </summary>
	public class Server
	{
		HttpListener serverSocket = null;
		
		bool remoteEnabled;
		int port;
		
		bool needStop;
		bool enabled;
		
		string wwwRootPath;

		public bool RemoteEnabled {
			get {
				return remoteEnabled;
			}
			set {
				remoteEnabled = value;
			}
		}

		public int Port {
			get {
				return port;
			}
			set {
				port = value;
			}
		}

		public bool NeedStop {
			get {
				return needStop;
			}
			set {
				needStop = value;
			}
		}

		public bool Enabled {
			get {
				return enabled;
			}
			set {
				enabled = value;
			}
		}

		public string WwwRootPath {
			get {
				return wwwRootPath;
			}
			set {
				wwwRootPath = value;
			}
		}
		
		public Server()
		{
			serverSocket = new HttpListener();
			
			remoteEnabled = false;
			port = 8080;
			
			needStop = false;
			enabled = false;
			
			wwwRootPath = ".";
		}
		
		public void Start()
		{
			string prefix = "http://";
			if (remoteEnabled)
			{
				prefix += "+";
			}
			else
			{
				prefix += "127.0.0.1";
			}
			prefix += ":" + port + "/";
			
			serverSocket.Prefixes.Add(prefix);
			serverSocket.Start();
			enabled = true;
			
			HttpListener socket = serverSocket;
			socket.BeginGetContext(new AsyncCallback(GetContextCallBack), socket);
		}
		
		public void Stop()
		{
			Logger.WriteLog("Server Stop!");
			enabled = false;
		}
		
		void GetContextCallBack(IAsyncResult ar)
		{
			try
			{
				var socket = ar.AsyncState as HttpListener;
				HttpListenerContext context = socket.EndGetContext(ar);
				
				socket.BeginGetContext(new AsyncCallback(GetContextCallBack), socket);
				
				if (enabled)
				{
					Deal(context);
				}
			}
			catch (Exception ex)
			{
				Logger.WriteError("Error happened: {0}", ex.Message);
			}
		}
		
		bool Deal(HttpListenerContext context)
		{
//			Logger.WriteDebug("Get one Context");
			
			// 模拟长时间的操作
//			System.Threading.Thread.Sleep(1000 * 6);
			
			var dealer = new HttpDealer(this, context.Request, context.Response);
			return dealer.Deal();
		}
	}
}
